/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package estg.dae.projecto.bank.data;

import estg.dae.projecto.bank.model.Client;
import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Marco
 */
@Stateless
public class ClientDao implements ClientDaoLocal {
    @PersistenceContext(unitName="Bank-ejb-PersistenceUnit")
    private EntityManager entityManager;

    public boolean exists(String nif) {
        return (Integer) entityManager.createQuery("SELECT COUNT(c) FROM Client c WHERE c.nif = ?1")
                .setParameter(1, nif)
                .getSingleResult() == (Integer) 1;
    }
    public Client get(String nif) {
        return (Client) entityManager.createQuery("SELECT c FROM Client c WHERE c.nif = ?1")
                .setParameter(1, nif)
                .getSingleResult();
    }
    public Client get(long id) {
        return entityManager.find(Client.class, id);
    }
    public void save(Client client){
        entityManager.persist(client);
        entityManager.flush();
        entityManager.clear();
    }
    public void update(Client client){
        entityManager.merge(client);
        entityManager.flush();
        entityManager.clear();
    }
    public void delete(Client client){
        entityManager.remove(client);
        entityManager.flush();
        entityManager.clear();
    }
    public Collection<Client> getAll(){
        return entityManager.createQuery("SELECT c FROM Client c")
                .getResultList();
    }
}
